package com.weichat.service.impl;

import com.weichat.dao.ProductInfoDao;
import com.weichat.dto.CartDTO;
import com.weichat.entity.ProductInfo;
import com.weichat.exception.SellException;
import com.weichat.service.ProductInfoService;
import com.weichat.util.ProductStatusEnum;
import com.weichat.util.ResultEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created with IntelliJ IDEA
 * Created By HZP
 * Date: 2018/6/6
 * Time: 22:43
 */
@Service
public class ProductInfoServiceImpl implements ProductInfoService {

    @Autowired
    private ProductInfoDao productInfoDao;

    @Override
    public List<ProductInfo> findAll() {
        return productInfoDao.findAll();
    }

    @Override
    public Page<ProductInfo> findAllPage(Pageable page) {
        return productInfoDao.findAll(page);
    }

    @Override
    public ProductInfo save(ProductInfo productInfo) {
        return productInfoDao.save(productInfo);
    }

    @Override
    public List<ProductInfo> findUpAll() {
        return productInfoDao.findByProductStatus(ProductStatusEnum.UP.getCode());
    }

    @Override
    public ProductInfo findOne(String integer) {

        return   productInfoDao.findById(integer).get();
    }

    @Override
    public void increaseStock(List<CartDTO> cartDTOLis) {

    }

    @Override
    @Transactional
    public void decreaseStock(List<CartDTO> cartDTOS) {
        for (CartDTO cartDTO:cartDTOS){
            ProductInfo productInfo=productInfoDao.findById(cartDTO.getProductId()).get();
            if (productInfo==null){
                throw new SellException(
                        ResultEnum.PRODUCT_NOT_EXIST
                );
            }
            Integer result=productInfo.getProductStock()-
                    cartDTO.getProductQuantity();
            if(result<0){
                throw new SellException(ResultEnum.PRODUCT_STOCK_ERROR);
            }
            productInfo.setProductStock(result);
            productInfoDao.save(productInfo);
        }
    }
}
